package com.mybatis.mybatisdatab.config;

import org.apache.tomcat.util.net.openssl.ciphers.Authentication;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;

@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Override
    //链式编程
    protected void configure(HttpSecurity http) throws Exception{
//        super.configure(http);
        //首页所有人可以访问，功能页只有对应权限的人可以访问
        /**
         * "/"代表首页
         */
        http.authorizeRequests().antMatchers("/").permitAll()
                .antMatchers("/level1**/").hasRole("vip1")
                .antMatchers("/level2**/").hasRole("vip2")
                .antMatchers("/level3**/").hasRole("vip3");

        //没有权限默认会到登录界面，需要开启登录的页面
        http.formLogin();

        // 注销.开启了注销功能，跳到首页
        http.logout().logoutSuccessUrl("/");
    }

    //认证 spring boot 2.1.x 直接可以使用
    @Override
    /**
     * 密码编码：passwordEncoder
     *
     * spring boot 5.0+ 新增了很多加密方法
     */
    public void configure(AuthenticationManagerBuilder auth) throws Exception {
        //这些数据正常应该从数据库中读取
        auth.inMemoryAuthentication().passwordEncoder(new BCryptPasswordEncoder())
                .withUser("mybatis").password(new BCryptPasswordEncoder().encode("123456")).roles("vip2","vip3")
                .and()
                .withUser("root").password(new BCryptPasswordEncoder().encode("123456")).roles("vip1","vip2","vip3")
                .and()
                .withUser("guest").password(new BCryptPasswordEncoder().encode("123456")).roles("vip1");
    }

}
